import React, { useEffect, Suspense } from 'react'
import { Routes, Route, Navigate } from 'react-router-dom'
import { useDispatch, useSelector } from 'react-redux'
import { Spin } from 'antd'
import { RootState } from '@/store'
import { getUserInfo, checkAuth } from '@/store/slices/authSlice'
import { fetchUserMenus } from '@/store/slices/menuSlice'
import { debugAuthState } from '@/utils/auth'
import { migrateStorage } from '@/utils/storage-migration'
import { useTheme } from '@/hooks/useTheme'
import Layout from '@/components/Layout'
import ErrorBoundary from '@/components/ErrorBoundary'
import { publicRoutes, privateRoutes } from '@/router'
import { RouteConfig } from '@/router/types'

// 扁平化路由配置，提取所有有组件的路由
const flattenRoutes = (routes: RouteConfig[]): RouteConfig[] => {
  const result: RouteConfig[] = []
  
  const flatten = (routeList: RouteConfig[]) => {
    routeList.forEach(route => {
      if (route.component) {
        result.push(route)
      }
      if (route.children) {
        flatten(route.children)
      }
    })
  }
  
  flatten(routes)
  return result
}

const App: React.FC = () => {
  const dispatch = useDispatch()
  
  // 使用主题 Hook 来应用主题设置
  useTheme()
  
  const { user, token, loading } = useSelector((state: RootState) => state.auth)
  const { menuList } = useSelector((state: RootState) => state.menu)

  // 应用启动时检查认证状态
  useEffect(() => {
    const initializeApp = async () => {
      // 执行存储迁移（清理旧键）
      await migrateStorage()
      
      // 开发环境下打印应用启动时的认证状态
      if (process.env.NODE_ENV === 'development') {
        console.log('🚀 [App] Starting authentication check...')
        debugAuthState()
      }
      
      dispatch(checkAuth() as any)
    }
    
    initializeApp()
  }, [dispatch])

  // 应用启动时，如果有token但没有用户信息，则获取用户信息
  useEffect(() => {
    if (token && !user) {
      dispatch(getUserInfo() as any)
    }
  }, [dispatch, token, user])

  // 当用户认证成功后，获取用户菜单数据
  // 使用useRef来跟踪是否已经发起过菜单请求，避免重复请求
  const menuRequestedRef = React.useRef(false)
  
  useEffect(() => {
    // 检查用户认证状态和菜单数据状态
    if (user && token && menuList.length === 0 && !loading && !menuRequestedRef.current) {
      menuRequestedRef.current = true // 标记已发起请求
      dispatch(fetchUserMenus() as any)
    }
    
    // 如果菜单数据已加载，重置请求标记
    if (menuList.length > 0) {
      menuRequestedRef.current = false
    }
  }, [dispatch, user, token, menuList.length, loading])

  // 显示加载状态
  if (loading) {
    return (
      <div style={{ 
        display: 'flex', 
        justifyContent: 'center', 
        alignItems: 'center', 
        height: '100vh',
        flexDirection: 'column'
      }}>
        <Spin size="large" />
        <div style={{ marginTop: 16, color: '#666' }}>正在加载用户信息...</div>
      </div>
    )
  }

  // 获取扁平化的路由配置
  const flatPublicRoutes = flattenRoutes(publicRoutes)
  const flatPrivateRoutes = flattenRoutes(privateRoutes)

  // 判断是否已认证：有token且有用户信息
  const isUserAuthenticated = Boolean(token && user)


  return (
    <ErrorBoundary>
      <Suspense fallback={
        <div style={{ 
          display: 'flex', 
          justifyContent: 'center', 
          alignItems: 'center', 
          height: '100vh',
          flexDirection: 'column'
        }}>
          <Spin size="large" />
          <div style={{ marginTop: 16, color: '#666' }}>加载中...</div>
        </div>
      }>
        <Routes>
          {/* 公共路由 */}
          {flatPublicRoutes.map(route => {
            const Component = route.component!
            return (
              <Route 
                key={route.path}
                path={route.path} 
                element={
                  isUserAuthenticated ? (
                    <>
                      <Navigate to="/" replace />
                    </>
                  ) : (
                    <>
                      <ErrorBoundary>
                        <Component />
                      </ErrorBoundary>
                    </>
                  )
                } 
              />
            )
          })}
          
          {/* 私有路由 - 认证后的所有页面 */}
          {isUserAuthenticated ? (
            <Route path="/*" element={<Layout useTabSystem={true} />}>
              {/* 根路径重定向到仪表盘 */}
              <Route index element={<Navigate to="/dashboard" replace />} />
              
              {/* 嵌套路由 */}
              {flatPrivateRoutes.map(route => {
                const Component = route.component!
                return (
                  <Route 
                    key={route.path}
                    path={route.path.startsWith('/') ? route.path.substring(1) : route.path} // 移除开头的斜杠
                    element={
                      <ErrorBoundary>
                        <Component />
                      </ErrorBoundary>
                    } 
                  />
                )
              })}
            </Route>
          ) : (
            <Route 
              path="/*" 
              element={<Navigate to="/login" replace />} 
            />
          )}
        </Routes>
      </Suspense>
    </ErrorBoundary>
  )
}

export default App